<template>
  <div class="payment-management">
    <el-card class="box-card">
      <div slot="header" class="clearfix">
        <span>支付管理</span>
        <div style="float: right;">
          <el-button 
            type="primary" 
            size="small" 
            icon="el-icon-plus"
            @click="handleAdd"
            style="margin-right: 8px;">
            新增支付渠道
          </el-button>
          <el-button 
            type="success" 
            size="small" 
            icon="el-icon-download"
            @click="exportData"
            :loading="exportLoading">
            导出CSV
          </el-button>
        </div>
      </div>

      <el-table
        :data="paymentMethods"
        border
        style="width: 100%"
        :header-cell-style="{ background: '#f5f7fa', color: '#606266' }"
        v-loading="loading"
      >
        <el-table-column prop="id" label="ID" width="80"></el-table-column>
        <el-table-column prop="name" label="支付名称" width="150"></el-table-column>
        <el-table-column prop="tag" label="支付标识" width="150"></el-table-column>
        <el-table-column prop="open" label="状态" width="120">
          <template slot-scope="scope">
            <el-switch
              :value="scope.row.open === 1"
              active-text="开启"
              inactive-text="关闭"
              @change="handleChangeStatus(scope.row, $event)"
            ></el-switch>
          </template>
        </el-table-column>
        <el-table-column label="操作" width="150">
          <template slot-scope="scope">
            <el-button
              size="mini"
              type="primary"
              @click="handleEdit(scope.row)">
              编辑
            </el-button>
          </template>
        </el-table-column>
      </el-table>
    </el-card>

    <!-- 新增/编辑弹窗 -->
    <el-dialog
      :title="dialogTitle"
      :visible.sync="dialogVisible"
      width="500px"
      @close="resetForm">
      <el-form
        :model="form"
        :rules="rules"
        ref="form"
        label-width="100px">
        <el-form-item label="支付名称" prop="name">
          <el-input v-model="form.name" placeholder="请输入支付名称"></el-input>
        </el-form-item>
        <el-form-item label="支付标识" prop="tag">
          <el-input v-model="form.tag" placeholder="请输入支付标识"></el-input>
        </el-form-item>
        <el-form-item label="状态" prop="open">
          <el-radio-group v-model="form.open">
            <el-radio :label="1">开启</el-radio>
            <el-radio :label="0">关闭</el-radio>
          </el-radio-group>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click="dialogVisible = false">取消</el-button>
        <el-button type="primary" @click="handleSubmit" :loading="submitLoading">
          {{ isEdit ? '更新' : '新增' }}
        </el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import { payChannel, payChannelOpen, payChannelAdd, payChannelEdit } from '@/api/user'
import { exportDataToCsv } from '@/utils/export'

export default {
  name: 'PaymentManagement',
  data() {
    return {
      paymentMethods: [],
      loading: false,
      exportLoading: false,
      dialogVisible: false,
      dialogTitle: '',
      isEdit: false,
      form: {
        id: '',
        name: '',
        tag: '',
        open: 1
      },
      rules: {
        name: [{ required: true, message: '请输入支付名称', trigger: 'blur' }],
        tag: [{ required: true, message: '请输入支付标识', trigger: 'blur' }]
      },
      submitLoading: false
    }
  },
  methods: {
    async handleChangeStatus(row, status) {
      this.loading = true
      try {
        const params = {
          id: row.id,
          open: status ? 1 : 0
        }
        
        const response = await payChannelOpen(params)
        
        if (response.code === 0) {
          // 更新本地数据
          row.open = status ? 1 : 0
          this.$message.success(`${row.name} 状态已更新为 ${status ? '开启' : '关闭'}`)
        } else {
          this.$message.error(response.msg || '更新失败')
          // 恢复原状态
          this.$forceUpdate()
        }
      } catch (error) {
        console.error('更新支付渠道状态失败:', error)
        this.$message.error('更新失败')
        // 恢复原状态
        this.$forceUpdate()
      } finally {
        this.loading = false
      }
    },
    async fetchData() {
      this.loading = true
      try {
        const response = await payChannel()
        
        if (response.code === 0) {
          this.paymentMethods = response.data.channels || []
        } else {
          this.$message.error(response.msg || '获取数据失败')
        }
      } catch (error) {
        console.error('获取支付渠道失败:', error)
        this.$message.error('获取数据失败')
      } finally {
        this.loading = false
      }
    },
    async exportData() {
      this.exportLoading = true
      try {
        const params = {
          channel: 0,
          page: 1,
          page_size: 10000
        }
        
        const response = await payChannel(params)
        const allData = response.data.pay_channels || []
        
        const columns = [
          { prop: 'Id', label: 'ID' },
          { prop: 'channel', label: '渠道' },
          { prop: 'type', label: '类型' },
          { prop: 'status', label: '状态', formatter: (row) => row.status === 1 ? '开启' : '关闭' }
        ]
        
        const now = new Date()
        const dateStr = now.getFullYear() + 
          String(now.getMonth() + 1).padStart(2, '0') + 
          String(now.getDate()).padStart(2, '0') + '_' +
          String(now.getHours()).padStart(2, '0') + 
          String(now.getMinutes()).padStart(2, '0')
        
        const fileName = `支付管理_${dateStr}.csv`
        exportDataToCsv(allData, columns, fileName)
        this.$message.success('导出成功！')
      } catch (error) {
        this.$message.error('导出失败')
        console.error(error)
      } finally {
        this.exportLoading = false
      }
    },
    handleAdd() {
      this.isEdit = false
      this.dialogTitle = '新增支付渠道'
      this.form = {
        name: '',
        tag: '',
        open: 1
      }
      this.dialogVisible = true
      // 清除表单验证
      this.$nextTick(() => {
        if (this.$refs.form) {
          this.$refs.form.clearValidate()
        }
      })
    },
    handleEdit(row) {
      this.isEdit = true
      this.dialogTitle = '编辑支付渠道'
      this.form = { 
        Id: row.Id,
        name: row.name,
        tag: row.tag,
        open: row.open
      }
      this.dialogVisible = true
      // 清除表单验证
      this.$nextTick(() => {
        if (this.$refs.form) {
          this.$refs.form.clearValidate()
        }
      })
    },
    resetForm() {
      if (this.$refs.form) {
        this.$refs.form.resetFields()
      }
    },
    async handleSubmit() {
      this.$refs.form.validate(async (valid) => {
        if (valid) {
          this.submitLoading = true
          try {
            let params
            let response
            
            if (this.isEdit) {
              // 修改接口参数 - 必须包含ID
              params = {
                Id: this.form.Id,
                name: this.form.name,
                tag: this.form.tag,
                open: this.form.open ? 1 : 0
              }
              response = await payChannelEdit(params)
            } else {
              // 新增接口参数 - 不包含ID
              params = {
                name: this.form.name,
                tag: this.form.tag,
                open: this.form.open ? 1 : 0
              }
              response = await payChannelAdd(params)
            }

            console.log('提交参数:', params)
            console.log('接口响应:', response)

            if (response && response.code === 0) {
              this.$message.success(`${this.isEdit ? '更新' : '新增'}成功！`)
              this.dialogVisible = false
              this.fetchData()
            } else {
              this.$message.error(response.msg || response.message || `${this.isEdit ? '更新' : '新增'}失败`)
            }
          } catch (error) {
            console.error(`${this.isEdit ? '更新' : '新增'}失败:`, error)
            this.$message.error(`${this.isEdit ? '更新' : '新增'}失败`)
          } finally {
            this.submitLoading = false
          }
        }
      })
    }
  },
  mounted() {
    this.fetchData()
  }
}
</script>

<style scoped>
.payment-management {
  padding: 20px;
}

.page-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 20px;
}
</style> 